# Definition for a binary tree node.
from typing import Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def maxAncestorDiff(self, root: Optional[TreeNode]) -> int:
        subtracts = []

        def dfs_min(node: Optional[TreeNode]) -> int:
            nonlocal subtracts

            if node is None:
                return 100000
            if node.left is None and node.right is None:
                return node.val
            min_left = dfs_min(node.left)
            min_right = dfs_min(node.right)

            if node.left:
                subtracts.append(abs(node.val - min_left))
            if node.right:
                subtracts.append(abs(node.val - min_right))
            return min(node.val, min_left, min_right)

        def dfs_max(node: Optional[TreeNode]) -> int:
            nonlocal subtracts

            if node is None:
                return 0
            if node.left is None and node.right is None:
                return node.val
            min_left = dfs_max(node.left)
            min_right = dfs_max(node.right)

            if node.left:
                subtracts.append(abs(node.val - min_left))
            if node.right:
                subtracts.append(abs(node.val - min_right))
            return max(node.val, min_left, min_right)

        # 一个节点，与其子节点差的绝对值的最大值，可能是跟子节点中最大值相减，也可能是跟子节点中最小值相减
        dfs_min(root)
        dfs_max(root)
        return max(subtracts)
